package cn.gzjp.modules.rice.service;

import java.math.BigDecimal;
import java.util.List;

import cn.gzjp.modules.rice.entity.ProductStyle;
import cn.gzjp.modules.rice.entity.RiceOrderDetail;
import cn.gzjp.modules.rice.entity.RiceProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.service.CrudService;
import cn.gzjp.modules.rice.entity.RiceOrder;
import cn.gzjp.modules.rice.dao.RiceOrderDao;

/**
 * 订单Service
 * @author zengcp
 * @version 2018-11-17
 */
@Service
@Transactional(readOnly = true)
public class RiceOrderService extends CrudService<RiceOrderDao, RiceOrder> {

	@Autowired
	private RiceOrderDetailService riceOrderDetailService;
	@Autowired
	private RiceProductService riceProductService;

	@Autowired
	private ProductStyleService productStyleService;

	public RiceOrder get(String id) {
		RiceOrder order =  super.get(id);
		RiceOrderDetail search = new RiceOrderDetail();
		search.setOrderId(order.getId());
		order.setOrderDetailList(riceOrderDetailService.findList(search));
		return order;
	}
	
	public List<RiceOrder> findList(RiceOrder riceOrder) {
		return super.findList(riceOrder);
	}
	
	public Page<RiceOrder> findPage(Page<RiceOrder> page, RiceOrder riceOrder) {
		return super.findPage(page, riceOrder);
	}
	
	@Transactional(readOnly = false)
	public void save(RiceOrder order) {
		RiceOrder m = get(order.getId());
		if(m!=null){
			super.save(order);
		}else{
			super.insert(order, order.getId());
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(RiceOrder riceOrder) {
		super.deleteByLogic(riceOrder);
	}

	@Transactional(readOnly = false)
    public void submit(RiceOrder order, String[] productIdArray,String[] styleIdArray,int[] numArray) {
		super.insert(order, order.getId());
		for(int i=0;i<productIdArray.length;i++){
			String productId = productIdArray[i];
			String styleId = styleIdArray[i];
			int num = numArray[i];
			RiceProduct product = riceProductService.get(productId);
			ProductStyle style = productStyleService.get(styleId);
			RiceOrderDetail detail = new RiceOrderDetail();
			detail.setOrderId(order.getId());
			detail.setOpenid(order.getId());
			detail.setProductId(product.getId());
			detail.setProductNum(num);
			detail.setDiscountPrice(style.getDiscountPrice().multiply(new BigDecimal(num)));
			detail.setProductPrice(style.getProductPrice().multiply(new BigDecimal(num)));
			riceOrderDetailService.save(detail);
		}
    }
}